#include "servertcp.h"

servertcp::servertcp(QObject *parent) :
    QObject(parent)
{
    tcpPort = 6666;

    if ( ! tcpServer.listen(QHostAddress::Any, tcpPort))
    {
        qDebug() << tcpServer.errorString();
    }

    connect(&tcpServer, SIGNAL(newConnection()), this, SLOT(newConnect()));
}

void servertcp::newConnect()
{
    tcpSocket = tcpServer.nextPendingConnection();
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
}

void servertcp::readMessage()
{
    QDataStream in(tcpSocket);
    in.setVersion(QDataStream::Qt_4_6);

    in >> clientAddress;
    in >> message;

    qDebug() << clientAddress << message;

    connect(tcpSocket, SIGNAL(disconnected()),
               tcpSocket, SLOT(deleteLater()));
    tcpSocket->disconnectFromHost();

    emit receive(message);
}

void servertcp::setPort(const qint16 &port)
{
    tcpPort = port;
}

void servertcp::setAddress(const QString &address)
{
    clientAddress = address;
}

